from django.shortcuts import render, redirect, reverse
from django.views import View

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from .forms import RegisterForm, LoginForm, ForgetPwdForm, ModifyPwdForm
from .models import UserProfileModel, EmailVerifyRecord
from operation.models import UserMessageModel

from utils.send_email import send_email


class CustomBackend(ModelBackend):
    """修改登录方法：邮箱或者用户名都可以登录"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfileModel.objects.get(Q(username=username)|Q(email=username))
        except:
            return None
        if user.check_password(password):
            return user


class ActiveUserView(View):
    """激活账号"""
    def get(self, request, active_code):
        # 判断验证码是否存在数据库
        all_recodes = EmailVerifyRecord.objects.filter(code=active_code)

        # 如果验证码和邮箱都对，修改用户状态为激活，否则返回错误信息
        if all_recodes:
            for recode in all_recodes:
                email = recode.email
                user = UserProfileModel.objects.get(email=email)
                user.is_active = True
                user.save()
        else:
            return render(request, 'active_fail.html')

        # 激活账号后返回登录页面
        return render(request, 'login.html')


class LoginView(View):
    """登录"""
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 验证登录表单
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get('username', '')
            pass_word = request.POST.get('password', '')
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect(reverse('index'))
                else:
                    return render(request, 'login.html', {'msg': '用户未激活'})
            else:
                return render(request, 'login.html', {'msg': '用户名或者密码错误'})
        else:
            return render(request, 'login.html', {'login_form': login_form})


class LogoutView(View):
    """退出登录"""
    def get(self, request):
        logout(request)
        return redirect(reverse("index"))



class RegisterView(View):
    """注册"""
    def get(self, request):
        register_form = RegisterForm()
        data = {
            'register_form': register_form
        }
        return render(request, 'register.html', data)

    def post(self, request):
        register_form = RegisterForm(request.POST)
        # 判断输入参数是否合法
        if register_form.is_valid():
            # 先验证邮箱是否存在
            email = request.POST.get('email', None)

            # 邮箱已存在，返回错误信息
            if UserProfileModel.objects.filter(email=email):
                return render(request, 'register.html', {'msg': '用户已存在', 'register_form': register_form})

            # 邮箱不存在，保存到数据库
            pwd = request.POST.get('password', None)
            obj = UserProfileModel()
            obj.username = email
            obj.email = email
            obj.password = make_password(pwd)
            obj.save()

            # 发送站内信息：欢迎注册
            message = UserMessageModel()
            message.username = obj.id
            message.message = '欢迎注册慕学在线网'
            message.save()

            # 发送邮件
            send_email(email, 'register')
            return render(request, 'login.html')
        else:
            return render(request, 'register.html', {'register_form': register_form})


class ForgetPwdView(View):
    """忘记密码"""
    def get(self, request):
        forget_form = ForgetPwdForm()
        data = {
            'forget_form': forget_form
        }
        return render(request, 'forgetpwd.html', data)

    def post(self, request):
        forget_form = ForgetPwdForm(request.POST)
        if forget_form.is_valid():
            email = request.POST.get('email', '')
            send_email(email, 'forget')
            return render(request, 'send_success.html')
        else:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})


class ResetView(View):
    """重置密码"""
    def get(self, request, active_code):
        all_recodes = EmailVerifyRecord.objects.filter(code=active_code)
        if all_recodes:
            for recode in all_recodes:
                email = recode.email
                return render(request, 'password_reset.html', { 'email': email })
        else:
            return render(request, 'active_fail.html')
        return render(request, 'login.html')


class ModifyPwdView(View):
    """更改密码"""
    def post(self, request):
        modify_form = ModifyPwdForm(request.POST)
        if modify_form.is_valid():
            pwd1 = request.POST.get('password1')
            pwd2 = request.POST.get('password2')
            email = request.POST.get('email')
            if pwd1 != pwd2:
                return render(request, 'password_reset.html', { 'email': email, 'msg': '密码不一致' })
            user = UserProfileModel.objects.get(email=email)
            user.password = make_password(pwd2)
            user.save()
            return redirect(reverse('login'))
        else:
            email = request.POST.get('email')
            return render(request, 'password_reset.html', { 'email': email, 'modify_form': modify_form })



class IndexView(View):
    """前台首页"""
    def get(self, request):
        return render(request, 'base.html')


class Info(View):
    def get(self, request):
        pass